package br.com.estevam.gallery.tools;

import java.io.File;
import java.io.Serializable;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.swing.text.DefaultFormatter;
import javax.swing.text.NumberFormatter;

public class Util implements Serializable{

	private static String ASSETS_PATH = "";
	private static String WEBAPPS_PATH = "";
	private static final String S = File.separator /* "\\" */;

	private static final long serialVersionUID = 5640439220908580519L;

	public static String getS(){
		return S;
	}

	public static String getAssetsPath(){
		if(isNullOrEmpty(ASSETS_PATH)){
			ASSETS_PATH = System.getProperty("user.dir") + S + "webapps" + S + "gallery" + S + "assets" + S;
			if(!(new File(ASSETS_PATH).canRead())){
				ASSETS_PATH = System.getProperty("user.dir") + S + "src" + S + "main" + S + "webapp" + S + "assets" + S;
				if(!(new File(ASSETS_PATH).canRead())){
					ASSETS_PATH = System.getProperty("jetty.home") + S + "webapps" + S + "gallery" + S + "assets" + S;	// jetty

				}
			}
		}
		return ASSETS_PATH;
	}

	public static String getWebappPath(){
		if(isNullOrEmpty(WEBAPPS_PATH)){
			WEBAPPS_PATH = System.getProperty("user.dir") + S + "webapps" + S + "gallery" + S ;
			if(!(new File(WEBAPPS_PATH).canRead())){
				WEBAPPS_PATH = System.getProperty("user.dir") + S + "src" + S + "main" + S + "webapp" + S;
				if(!(new File(WEBAPPS_PATH).canRead())){
					WEBAPPS_PATH = System.getProperty("jetty.home") + S + "webapps" + S + "gallery" + S;	// jetty
				}
			}
		}
		return WEBAPPS_PATH;
	}


	public static synchronized void getArquivos(String path, List<String> arquivos){
		//		File f = new File(path.substring(1));
		File f = new File(path);

		String[] s = f.list();
		for(int i = 0; i < s.length; i++){
			String path2 = path + S + s[i];
			File dir = new File(path2);
			if(dir.isDirectory()){
				getArquivos(path2, arquivos);
			} else {
				arquivos.add(s[i]);
			}
		}
	}

	public static synchronized void limparDiretorio(String path){
		File diretorio = new File(path);
		String[] arquivos = diretorio.list();

		if(arquivos != null){
			for(int i = 0; i < arquivos.length; i++){
				if (!arquivos[i].equalsIgnoreCase("placeholder")){
					File f = new File(path + arquivos[i]);

					//Apagando arquivos criados a mais de 15 minutos.
					if (new Date().getTime() - f.lastModified() >= 900000){
						f.delete();
					}
				}					
			}
		}
	}

	public static synchronized boolean isNullOrEmpty(String string) {
		if (string == null) {
			return true;
		}
		if (string.trim().equals("")) {
			return true;
		}
		return false;
	}

	public static synchronized boolean isNullPointerString(String string) {
		try {
			return true;
		}
		catch (NullPointerException e){ 
			return false;
		}
	}

	public static synchronized String getPageName(String thisToString) {
		String pageName = thisToString;
		pageName = pageName.substring(pageName.lastIndexOf("pages.") + 6, pageName.indexOf('@'));
		pageName = pageName.replace('.', '/');
		return pageName;
	}

	public static synchronized String getPageName(Object page) {
		return (page.getClass().getName().substring(page.getClass().getName().lastIndexOf('.') + 1));
	}

	public static synchronized String fixFormat(String number) {
		String aux = "";

		if(number != null){
			if(number.indexOf(',') == -1){
				return "0." + number;
			}

			for(int i = 0; i < number.length(); i++){
				if(number.charAt(i) != '.'){
					aux = aux + number.charAt(i);
				}
			}

			aux = aux.replace(',', '.');
		}

		return aux;
	}

	public static synchronized String getMoneyConvert(String preco) { 
		DefaultFormatter formatter = new NumberFormatter(new DecimalFormat("#,##0.00"));
		String valor = "";

		try {
			valor = formatter.valueToString(new Double(preco));
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}       

		return valor;
	}

	public static String formatCnpjOuCpf(String number, String format){
		String subFormat = "";
		int tamanho = 0;
		number = number.trim();

		if(format.equals("cpf")){
			subFormat = "###.###.###-##";
			tamanho = 11;
		} else {
			subFormat = "##.###.###/####-##";
			tamanho = 14;
		}

		if(format.equals("cpf") || format.equals("cnpj")){
			String[] formatArray = new String[subFormat.length()];
			String[] resultArray = new String[subFormat.length()];
			String res = "";
			int subNumber = 0;
			int sub = 0;

			subNumber = (tamanho - number.length());
			String[] numberArray = new String[ (number.length() + subNumber) ];

			if (number.equals("")){
				return "-";
			}

			if(!(number.length() > tamanho)) {
				if(!(number.toString().length() == 0)){
					if (!(number.length() == 14)){
						for(int i = number.length(); i < (number.length() + subNumber); i++){
							numberArray[i] = "?";
						}
					}

					for (int i = 0; i < number.length(); i++)
						numberArray[i] = number.substring(i, i+1);

					for (int i = 0; i < subFormat.length(); i++){
						formatArray[i] = subFormat.substring(i, i+1);
						if(formatArray[i].equals("#")) {
							resultArray[i] = numberArray[sub];
							sub = sub + 1;
						} else { resultArray[i] = formatArray[i]; }
						res = res + resultArray[i];
					}
					return res;
				}
			} else {
				for (int i = 0; i < tamanho; i++)
					numberArray[i] = number.substring(i, i+1);
				for (int i = 0; i < subFormat.length(); i++){
					formatArray[i] = subFormat.substring(i, i+1);
					if(formatArray[i].equals("#")) {
						resultArray[i] = numberArray[sub];
						sub = sub + 1;
					} else { resultArray[i] = formatArray[i]; }
					res = res + resultArray[i];
				}
				return res+"...";
			}
		}
		return null;
	}

	public static synchronized boolean EqualsWithoutAccent(String base, String text){
		String acentuado = "çÇáéíóúýÁÉÍÓÚÝàèìòùÀÈÌÒÙãõñäëïöüÿÄËÏÖÜÃÕÑâêîôûÂÊÎÔÛ,.";
		String semAcento = "cCaeiouyAEIOUYaeiouAEIOUaonaeiouyAEIOUAONaeiouAEIOU  ";
		char[] tabela;

		tabela = new char[256];
		for (int i = 0; i < tabela.length; ++i) {
			tabela [i] = (char) i;
		}
		for (int i = 0; i < acentuado.length(); ++i) {
			tabela [acentuado.charAt(i)] = semAcento.charAt(i);
		}

		/**
		 *  Inicio Base
		 */
		StringBuffer sbBase = new StringBuffer();
		for (int i = 0; i < base.length(); ++i) {
			char ch = base.charAt (i);
			if (ch < 256) {
				sbBase.append(tabela[ch]);
			} else {
				sbBase.append(ch);
			}
		}
		String viceBase = "";
		String[] arrBase = sbBase.toString().split(" ");
		for(int i = 0; i < arrBase.length; i++){
			viceBase += arrBase[i];
		}
		/**
		 *  Fim Base
		 */

		/**
		 * Inicio Text
		 */
		StringBuffer sbText = new StringBuffer();
		for (int i = 0; i < text.length(); ++i) {
			char ch = text.charAt (i);
			if (ch < 256) { 
				sbText.append(tabela[ch]);
			} else {
				sbText.append(ch);
			}
		}
		String viceText = "";
		String[] arrText = sbText.toString().split(" ");
		for(int i = 0; i < arrText.length; i++){
			viceText += arrText[i];
		}
		/**
		 *  Fim Text
		 */

		return viceBase.equalsIgnoreCase(viceText);
	}

	public static synchronized String removerAcentos(String str){
		String acentuado = "çÇáéíóúýÁÉÍÓÚÝàèìòùÀÈÌÒÙãõñäëïöüÿÄËÏÖÜÃÕÑâêîôûÂÊÎÔÛ,.";
		String semAcento = "cCaeiouyAEIOUYaeiouAEIOUaonaeiouyAEIOUAONaeiouAEIOU  ";
		char[] tabela;

		tabela = new char[256];
		for (int i = 0; i < tabela.length; ++i) {
			tabela [i] = (char) i;
		}
		for (int i = 0; i < acentuado.length(); ++i) {
			tabela [acentuado.charAt(i)] = semAcento.charAt(i);
		}

		StringBuffer sbBase = new StringBuffer();
		for (int i = 0; i < str.length(); ++i) {
			char ch = str.charAt (i);
			if (ch < 256) {
				sbBase.append(tabela[ch]);
			} else {
				sbBase.append(ch);
			}
		}

		return sbBase.toString();

	}

	public static synchronized SimpleDateFormat getDateFormat(){
		return new SimpleDateFormat("dd/MM/yyyy");
	}

	/**
	 * 
	 * algoritmo vai escolher MD5, SHA1 e SHA254
	 * 
	 * @param sign
	 * @param algoritmo
	 * @return
	 */
	public static String encrypt(byte[] sign, String algoritmo) {   
		StringBuffer hexString = new StringBuffer();
		try {   
			MessageDigest md = MessageDigest.getInstance(algoritmo);   
			md.update(sign);   
			byte[] hash = md.digest();   
			for (int i = 0; i < hash.length; i++) {   
				if ((0xff & hash[i]) < 0x10)   
					hexString.append("0" + Integer.toHexString((0xFF & hash[i])));   
				else   
					hexString.append(Integer.toHexString(0xFF & hash[i]));   
			}   
		}   
		catch (Exception nsae) {   
			nsae.printStackTrace();   
		}   
		return hexString.toString();   
	}  
}
